//
//  MYGAcademicConferenceLiverRootVC.swift
//  MYDoctor
//
//  Created by Denny on 2024/5/27.
//

import UIKit
import JXSegmentedView
import AVFoundation
class MYGAcademicConferenceLiverRootVC: MYGBaseController {

    private var secondStr:Int = 0
    private var minitStr:Int = 0
    private var hourStr :Int = 0
    private var dayStr :Int = 0
    private var timer:Timer!
    private var liveUrl:String = ""
    
    var meeting_id = ""
    var topImageUrl = ""
    var sing_count = 0
    var isHiddenBtn:Bool = false
    var segmentedDataSource: JXSegmentedTitleDataSource = {
        let control = JXSegmentedTitleDataSource()
        control.titles = ["详情","互动"]
        control.isTitleColorGradientEnabled = true
        control.isTitleZoomEnabled = true
        control.titleNormalColor = UIColor.init(hexString: "#767676")
        control.titleSelectedColor = UIColor.init(hexString: "#2c2c2c")
        return control
    }()
    
    lazy var liveVC:MYGAcademicConferenceLiveVC = {
        let control = MYGAcademicConferenceLiveVC()
        control.meeting_id = self.meeting_id
        control.liveStatutBlock = { [self] (liveState,url,startTime) in
            avPlayer.pause()
            avPlayer.stop()
            avPlayer.isHidden = true
            playBtn.isHidden = false
            topImageView.isHidden = false
            timeTipview.isHidden = true
            if (timer != nil) {
                self.timer?.invalidate()
                timer = nil
            }
            
            switch liveState {
            case .live:
               print("直播中 \(url)")
                liveUrl = url
            case .liveEnd:
                print("直播结束 \(url)")
                liveUrl = url
            case .liveNoStart:
                print("直播未开始")
                playBtn.isHidden = true
                timeTipview.isHidden = false
                time(startTime: startTime)
            }
            
        }

        return control
    }()
    
    private func time(startTime:String){
     
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        //会议开始时间
        let endDate = dateFormatter.date(from: startTime)
        
        //当前时间
        let currentDate = Date.init()
        
        let calendar = Calendar.current
        let unit:Set<Calendar.Component> = [.day,.hour,.minute,.second]
        let commponent:DateComponents = calendar.dateComponents(unit, from: currentDate, to: endDate!)
        
        print(commponent.day as Any,commponent.hour as Any,commponent.minute as Any,commponent.second as Any)
        secondStr = commponent.second!
        minitStr = commponent.minute!
        hourStr = commponent.hour!
        dayStr = commponent.day!
        
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        RunLoop.main.add(timer!, forMode: .common)
    }
    
   @objc func timerAction() {
       secondStr = secondStr - 1
           if secondStr == -1 {
               secondStr = 59
               minitStr = minitStr - 1
               if minitStr == -1 {
                   minitStr = 59
                   hourStr = hourStr - 1
                   if hourStr == -1 {
                       hourStr = 23
                       dayStr = dayStr - 1
                   }
               }
           }
           
       if  secondStr == 0 && minitStr == 0 && hourStr == 0 && dayStr == 0 {
               self.timer?.invalidate()
               timer = nil
           }
           
//        print(dayStr as Any,hourStr as Any,minitStr as Any,secondStr as Any)
       timeTipview.dayLB.text = String(dayStr)
       timeTipview.hourLB.text = String(hourStr)
       timeTipview.minLB.text = String(minitStr)
       timeTipview.secondLB.text = String(secondStr)
       }
    
    private lazy var avPlayer: CLPlayer = {
        let view = CLPlayer(frame: .zero) { config in
            config.rotateStyle = .none
        }
        
        return view
    }()
    
    let timeTipview: MYGAcademicReserveTipView = {
        let control = Bundle.main.loadNibNamed("MYGAcademicReserveTipView", owner: nil)?.first as! MYGAcademicReserveTipView
        return control
    }()
    
    lazy var interactVC:MYGAcademicConferenceLiverInteractVC = {
        let control = MYGAcademicConferenceLiverInteractVC()
        control.meeting_id = self.meeting_id
        return control
    }()
    lazy var segment:JXSegmentedView = {
         let control  = JXSegmentedView()
         control.delegate = self
         return control
     }()
    
    var topImageView:UIImageView = {
        let control = UIImageView()
        return control
    }()
    lazy var textInputView:MYGAcademicConferenceInteractInputView = {
        let control = MYGAcademicConferenceInteractInputView()
        control.tapSendCompeltion = { [self]text in
            sendComment(text)
        }
        control.tapCancelCompeltion = {
            
        }
        return control
    }()
    
    private lazy var playBtn:UIButton = {
        let playB = UIButton()
        playB.setImage(UIImage(named: "MYG_home_play"), for: .normal)
        playB.addTarget(self, action: #selector(clickPlayer), for: .touchUpInside)
        return playB
    }()
    
    lazy var toolBar:MYGAcademicConferenceInteractToolBar = {
        let control = MYGAcademicConferenceInteractToolBar()
        control.isHidden = true
        control.tapCompletion = {[weak self] in
            guard let `self` = self else{return}
            self.textInputView.titleLB.text = "提问"
            self.textInputView.contentTF.becomeFirstResponder()
        }
        return control
    }()
    @objc func keyboardWillShow(_ noti:Notification) {
        if let keyboardSize = (noti.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = keyboardSize.height
            self.textInputView.snp.updateConstraints({ make in
                make.bottom.equalToSuperview().offset(-keyboardHeight)
                make.left.right.equalToSuperview()
                make.height.equalTo(200)
            })
        } 
    }
    
    @objc func keyboardWillHide(_ sender: Notification) { 
        self.textInputView.snp.updateConstraints({ make in
            make.bottom.equalToSuperview().offset(200)
            make.left.right.equalToSuperview()
            make.height.equalTo(200)
        })
    }
    @objc func toShare() {
        MYGCloudDiskPopManager.showComonShare(self.view,meeting_id: meeting_id)
    }
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
        self.timer?.invalidate()
        timer = nil
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        avPlayer.pause()
        avPlayer.stop()
        
        self.timer?.invalidate()
        timer = nil
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "会议详情"
        let rightItem = UIBarButtonItem(image: UIImage(named: "academicConference_share"), style: .plain, target: self, action: #selector(toShare))
//        navigationItem.rightBarButtonItem = rightItem
        
        topImageView.sd_setImage(with: URL(string: topImageUrl), placeholderImage: UIImage(named: "MYG_health_bg"))

        configSegMent()
        timeTipview.meeting_id = meeting_id
        timeTipview.countLB.text = " 已预约人数: \(sing_count)"
        timeTipview.reserveBtn.isHidden = isHiddenBtn
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)),name:UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
        
    }
    
    func configSegMent() {
        view.backgroundColor = .white
        view.addSubview(topImageView)
        topImageView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(184)
        }
        
        view.addSubview(playBtn)
        playBtn.snp.makeConstraints { make in
            make.left.equalTo(17.5)
            make.width.height.equalTo(25)
            make.bottom.equalTo(topImageView.snp.bottom).offset(-10)
        }
        playBtn.isHidden = true
        
        view.addSubview(avPlayer)
        avPlayer.snp.remakeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(184)
        }
        avPlayer.isHidden = true
        
        view.addSubview(timeTipview)
        timeTipview.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(120)
            make.left.right.equalToSuperview()
            make.height.equalTo(66)
        }
        timeTipview.isHidden = true
        
        self.view.addSubview(segment)
        segment.snp.makeConstraints { make in
            make.top.equalTo(topImageView.snp.bottom)
            make.left.equalToSuperview()
            make.height.equalTo(46.5)
            make.width.equalToSuperview()
        }
        //关联dataSource
        segment.dataSource = self.segmentedDataSource
        
        let indicator = JXSegmentedIndicatorImageCustonmView()
        indicator.image = UIImage.init(named: "indie_icon")
        segment.indicators = [indicator]
        
        let listContainerView = JXSegmentedListContainerView(dataSource: self)
        view.addSubview(listContainerView)
        listContainerView.snp.makeConstraints { make in
            make.top.equalTo(segment.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        //关联listContainer
        segment.listContainer = listContainerView
        
        view.addSubview(toolBar)
        toolBar.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(bottomSafeheight + 46)
        }
        
        view.addSubview(textInputView)
        textInputView.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(200)
            make.left.right.equalToSuperview()
            make.height.equalTo(200)
        }
    }
  
   
}

extension MYGAcademicConferenceLiverRootVC {
    
    @objc func clickPlayer() {
        print("播放视频")
        
        playBtn.isHidden = true
        topImageView.isHidden = true
        avPlayer.isHidden = false
        
        avPlayer.url = URL(string: liveUrl)
        avPlayer.play()

    }
    
    //评论
    func sendComment(_ text:String) {
        let params = ["user_type":"1","data_id":meeting_id,"type":"9","content":text]
        MYGLoading.show()
        MYGNetwork<MYGMeAPI, MYGTopicCommentModel>.request(target: .commentSubmit(param:params)) {  item in
            MYGLoading.hide()
            MMYGHUD.showToast(text: "发布成功")
            NotificationCenter.default.post(name: NSNotification.Name.init("MYGAcafemicCommentList"), object: nil)
        
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
}

extension MYGAcademicConferenceLiverRootVC : JXSegmentedListContainerViewDataSource {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return segmentedDataSource.titles.count
    }
    
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        if index == 0 {
            return self.liveVC
        }
        
        return self.interactVC
    }

}
extension MYGAcademicConferenceLiverRootVC: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
//        selectedIndex = index
        toolBar.isHidden = index == 0
    }
}
